package com.yj.springbootzookeeper.config;

import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ZkConfig implements InitializingBean, BeanPostProcessor {


    private static final int BASE_SLEEP_TIME = 1000; //重试之间等待的初始时间
    private static final int MAX_RETRIES = 3;   //最大重试次数

    public static void main(String[] args) throws Exception {
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(BASE_SLEEP_TIME, MAX_RETRIES);
        CuratorFramework zkClient = CuratorFrameworkFactory.builder()
                .connectString("192.168.152.11:2181")//要连接的服务器列表
                .retryPolicy(retry)//重试策略
                .build();
        zkClient.start();
        //创建节点
        // 1、持久节点：一旦创建就一直存在，即是Zookeeper 集群宕机，直到将它删除。
        // 2、持久顺序节点：除了具备持久节点的特性之外，子节点的名称还具有顺序性。
        // 3、临时节点：临时节点的生命周期和客户端会话绑定，会话消失则节点消失。临时节点只能做叶子节点，不能创建子节点。
        // 4、临时顺序节点：除了具备临时节点的特性之外，子节点的名称还具有顺序性。

        //a-创建持久化节点,creatingParentsIfNeeded 如果父节点不存在则创建
        //zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/node1/001");

        //b-创建临时节点
        //zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/node1/002");

        //c-创建临时节点并指定数据内容
        //zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/node1/003","hello zookeeper".getBytes());
        //zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/node1/003","hello zookeeper".getBytes());

        //d-获取指定节点的数据
        byte[] bytes = zkClient.getData().forPath("/node1/003");
        System.out.println(new String(bytes,"utf-8"));

        //e-删除一个子节点
//        zkClient.delete().forPath("/node1/001");

        //f-获取某个节点的所有子节点路径
        List<String> list = zkClient.getChildren().forPath("/");
        System.out.println(list);


    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("test1111111111111111111");
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }
}
